<template>
  <div
    class="com_container"
    style="position: relative;"
  >
    <div
      class="com_eachrt"
      ref="echart"
    >
    </div>
  </div>
</template>

<script>
import { getAction } from '@/api/manage';
import '@/assets/echart/theme/chalk';
export default {
  data() {
    return {
      //echartInstance实例类
      chartInstance: null,
      //数据集合
      dataList: null,
      // 区域缩放的起点值
      startValue: 0,
      // 区域缩放的终点值
      endValue: 9,
      // 定时器的标识
      timerId: null,
    };
  },
  mounted() {
    this.initEchart();
    this.getData();
    //设置监听事件，监听窗口大小动态改变echart的大小（注意销毁）
    window.addEventListener('resize', this.screenAdapter);
    // 在页面加载完成的时候, 主动进行屏幕的适配
    this.screenAdapter();
  },
  computed: {},
  methods: {
    //初始化echart
    initEchart() {
      //初始化echart对象，并指明主题
      this.chartInstance = this.$echarts.init(this.$refs.echart, 'chalk');
      const initOption = {
        title: {
          text: '▎ 地区销售排行',
          left: 20,
          top: 20,
        },
        xAxis: {
          type: 'category',
        },
        yAxis: {
          type: 'value',
        },
        series: [
          {
            type: 'bar',
          },
        ],
        //表格位置设置
        grid: {
          top: '40%',
          left: '5%',
          right: '5%',
          bottom: '5%',
          containLabel: true,
        },
        //鼠标移入工具提示
        tooltip: {
          show: true,
        },
      };
      this.chartInstance.setOption(initOption);
      this.chartInstance.on('mouseover', () => {
        clearInterval(this.timerId);
      });
      this.chartInstance.on('mouseout', () => {
        this.startInterval();
      });
    },
    //获取服务器数据
    async getData() {
      const { data: resArr } = await getAction('/echart/getJson', {
        fileName: 'rank.json',
      });
      this.dataList = resArr;
      // 对allData里面的每一个元素进行排序, 从大到小进行
      this.dataList.sort((a, b) => {
        return b.value - a.value;
      });
      //更新echart
      this.updateChart();
      //启动定时
      this.startInterval();
    },
    //更新echart
    updateChart() {
      //柱子颜色
      const colorArr = [
        ['#0BA82C', '#4FF778'],
        ['#2E72BF', '#23E5E5'],
        ['#5052EE', '#AB6EE5'],
      ];
      // 所有省份所形成的数组
      const provinceArr = this.dataList.map((item) => {
        return item.name;
      });
      // 所有省份对应的销售金额
      const valueArr = this.dataList.map((item) => {
        return item.value;
      });
      const dataOption = {
        xAxis: {
          data: provinceArr,
        },
        //区域缩放
        dataZoom: {
          show: false,
          startValue: this.startValue,
          endValue: this.endValue,
        },
        series: [
          {
            data: valueArr,
            itemStyle: {
              color: (arg) => {
                let targetColorArr = null;
                if (arg.value > 300) {
                  targetColorArr = colorArr[0];
                } else if (arg.value > 200) {
                  targetColorArr = colorArr[1];
                } else {
                  targetColorArr = colorArr[2];
                }
                return new this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  {
                    offset: 0,
                    color: targetColorArr[0],
                  },
                  {
                    offset: 1,
                    color: targetColorArr[1],
                  },
                ]);
              },
            },
          },
        ],
      };
      this.chartInstance.setOption(dataOption);
    },
    // 当浏览器的大小发生变化的时候, 会调用的方法, 来完成屏幕的适配
    screenAdapter() {
      // 和分辨率大小相关的配置项
      let titleFontSize = (this.$refs.echart.offsetWidth / 100) * 3.6;
      console.log('titleFontSize', titleFontSize);
      const adapterOption = {
        title: {
          textStyle: {
            fontSize: titleFontSize,
          },
        },
        series: [
          {
            barWidth: titleFontSize,
            itemStyle: {
              //柱子的圆角设置（分别是：左上、右上、右下、左下）
              borderRadius: [titleFontSize / 2, titleFontSize / 2, 0, 0],
            },
          },
        ],
      };
      this.chartInstance.setOption(adapterOption);
      // 手动的调用图表对象的resize 才能产生效果
      this.chartInstance.resize();
    },
    //启动定时
    startInterval() {
      if (this.timerId) {
        clearInterval(this.timerId);
      }
      this.timerId = setInterval(() => {
        this.startValue++;
        this.endValue++;
        if (this.endValue > this.dataList.length - 1) {
          this.startValue = 0;
          this.endValue = 9;
        }
        this.updateChart();
      }, 2000);
    },
  },
  destroyed() {
    //销毁监听事件
    window.removeEventListener('resize', this.screenAdapter);
    //消除定时
    clearInterval(this.timerId);
  },
};
</script>

<style lang="scss" scoped>
.drop {
  position: absolute;
  left: 20px;
  top: 20px;
  z-index: 10;
  .el-dropdown-link {
    cursor: pointer; //鼠标悬浮变小手
  }
  .el-dropdown {
    font-size: 24px;
    color: white;
  }
}
</style>